#include <webx/route.h>

class ShareNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ShareNote, "/compile/${filename}")

int ShareNote::process()
{
	param_string(id);
	param_string(dbid);
	param_string(user);
	param_string(title);
	param_string(folder);

	if (id.empty() && title.empty())
	{
		clearResponse();
		
		return XG_PARAMERR;
	}

	try
	{
		checkLogin();
	}
	catch(Exception e)
	{
	}

	auto getUser = [&](){
		return token && user.empty() ? token->getUser() : user;
	};

	auto getDataId = [&](){
		return token && dbid.empty() ? token->getDataId() : dbid;
	};

	JsonEntity(Result)
	{
		rint(level);
		rstring(user);
		rstring(content);
	};

	Result result;
	sp<DBConnect> dbconn;

	if (id.empty())
	{
		if (folder.empty())
		{
			string sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE FOLDER='WEBPAGE' AND TITLE=?";

			webx::GetDBConnect(dbid)->select(result, sqlcmd, title);
		}
		else
		{
			string sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE USER=? AND FOLDER=? AND TITLE=?";

			webx::GetDBConnect(getDataId())->select(result, sqlcmd, getUser(), folder, title);
		}
	}
	else
	{
		string sqlcmd = "SELECT USER,LEVEL,CONTENT FROM T_XG_CODE WHERE ID=?";

		webx::GetDBConnect(getDataId())->select(result, sqlcmd, id);
	}
	
	if (result.user.empty()) return XG_NOTFOUND;

	if (result.user == getUser() || result.level > 2)
	{
		out << result.content;
	}

	return XG_OK;
}